import launch
import launch_ros
from ament_index_python.packages import get_package_share_directory
import os
import launch_ros.parameter_descriptions

def generate_launch_description():
    urdf_packge_path=get_package_share_directory('firstrobot_description')
    default_urdf_path=os.path.join(urdf_packge_path,'urdf','first_robot.urdf')
    default_rviz2config_path=os.path.join(urdf_packge_path,'config','fisrtrobot_displaymodel.rviz')
    
    #声明一个urdf目录的参数方便修改
    action_declare_arg_mode_path=launch.actions.DeclareLaunchArgument(
        name='model',default_value=str(default_urdf_path),description='加载文件路径'
    )


    # 通过文件路径获取内容，并转换成参数对象，并传入robot_state_publisher
    subscription_command_result = launch.substitutions.Command(
    ['xacro ', launch.substitutions.LaunchConfiguration('model')]# 禁用shell模式以避免参数合并
    )
    # with open(default_urdf_path, 'r') as f:
    #     urdf_content = f.read()
    # robot_description_value = launch_ros.parameter_descriptions.ParameterValue(urdf_content, value_type=str)

    robot_description_value=launch_ros.parameter_descriptions.ParameterValue(
        subscription_command_result,value_type=str)
    print(robot_description_value)


    action_robot_state_publisher=launch_ros.actions.Node(
        package='robot_state_publisher',
        executable='robot_state_publisher',
        parameters=[{'robot_description':robot_description_value}]
    )

    action_joint_state_publisher=launch_ros.actions.Node(
    package='joint_state_publisher',
    executable='joint_state_publisher',
      
    )

    action_rviz2_node=launch_ros.actions.Node(
        package='rviz2',
        executable='rviz2',
        arguments=['-d',default_rviz2config_path]
    )
    return launch.LaunchDescription([
        action_declare_arg_mode_path,
        action_robot_state_publisher,
        action_joint_state_publisher,
        action_rviz2_node,


    ])